package blf.librarysystem.Utils;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component //标记该类为主键
public class AdminLoginInterceptor implements HandlerInterceptor {

//    调用所有Controller之前实现这个方法，如果为true则继续执行，false则中断后续操作
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String servletPath = request.getServletPath(); //获取当前路由
        //如果路由是以admin作为开头，并且没有设置过name的session属性，则进行拦截
        if (servletPath.startsWith("/admin") && request.getSession().getAttribute("name") == null) {
            request.getSession().setAttribute("errorMsg", "请先登录!");
            response.sendRedirect( "/admin/login");
            return false;
        } else {
            request.getSession().removeAttribute("errorMsg");
            return true;
        }
    }

    //调用Controller之后，返回视图解析之前实现这个方法，可用于对对视图解析的进一步修改
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    //调用Controller并返回视图解析后实现这个方法
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
